import uvicorn
import logging
import os
import sys
from dotenv import load_dotenv
from pathlib import Path

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)

# Load environment variables
logger.info("Loading environment variables...")
load_dotenv(".env.local")

# Check for AZURE_OPENAI_API_KEY
api_key = os.environ.get("AZURE_OPENAI_API_KEY")
if not api_key:
    logger.warning(
        "AZURE_OPENAI_API_KEY not found in environment. "
        "Please add it to .env.local file or set it as an environment variable."
    )

# Ensure directories exist
logger.info("Ensuring directories exist...")
Path("knowledge_base").mkdir(exist_ok=True)
Path("index_storage").mkdir(exist_ok=True)
Path("static").mkdir(exist_ok=True)

if __name__ == "__main__":
    logger.info("Starting the RAG demo application...")
    try:
        uvicorn.run(
            "app.main:app",
            host="0.0.0.0",
            port=8000,
            reload=True,
            log_level="info"
        )
    except Exception as e:
        logger.error(f"Error starting application: {e}")
        raise 